package com.youhome.config;

import com.alibaba.fastjson.JSON;
import com.youhome.response.Result;
import com.youhome.response.ResultCode;
import com.youhome.service.AuthenticationService;
import com.youhome.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * Token 过滤器
 * Created by chen365 on 2018/09/12.
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    AuthenticationService authenticationService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();

        String token = request.getHeader("token");
        System.err.println("token:" + token);
        Boolean isFilter = true;
        if (token != null) {
            String username = jwtTokenUtil.getUsernameFromToken(token);
            System.err.println("username:" + username);
            Result result = null;

            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = authenticationService.loadUserByUsername(username);
                if (jwtTokenUtil.validateToken(token, userDetails)) {

                    SMSAuthenticationToken authentication = new SMSAuthenticationToken(userDetails, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);

                    jwtTokenUtil.refreshToken(token); //刷新token
                } else {
                    isFilter = false;
                    System.err.println("token不正确！");
                    result = new Result(ResultCode.UNAUTHORIZED);
                }
            } else {
                isFilter = false;
                System.err.println("token不存在！");
                result = new Result(ResultCode.UNAUTHORIZED);
            }

            if (result!= null && result.getStatus() > 0) {// 验证失败
                PrintWriter writer = null;
                OutputStreamWriter osw = null;
                try {
                    osw = new OutputStreamWriter(response.getOutputStream(),"UTF-8");
                    writer = new PrintWriter(osw, true);
                    String jsonStr = JSON.toJSONString(result);
                    writer.write(jsonStr);
                    writer.flush();
                    writer.close();
                    osw.close();
                } catch (UnsupportedEncodingException e) {
                    logger.error("过滤器返回信息失败:" + e.getMessage(), e);
                } catch (IOException e) {
                    logger.error("过滤器返回信息失败:" + e.getMessage(), e);
                } finally {
                    if (null != writer) {
                        writer.close();
                    }
                    if (null != osw) {
                        osw.close();
                    }
                }
                return;
            }
        }
        if (isFilter) {
            filterChain.doFilter(request, response);
        }
    }
}
